//
//  RealNameViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/10.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "RealNameViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
@interface RealNameViewController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
{
    UIImageView *firstImgview;
    UIImageView *secondImgview;
    UIImageView *thirdImgview;

}
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *carNum;
@property (nonatomic, strong)NSString *imageFirst;
@property (nonatomic, strong)NSString *imageSecond;
@property (nonatomic, strong)NSString *imageThird;
@property (nonatomic, assign)NSInteger phoneType;
@property (nonatomic, strong)UIImage *firstImg;
@property (nonatomic, strong)UIImage *secondImg;
@property (nonatomic, strong)UIImage *thirdImg;

@end

@implementation RealNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _name = @"";
    _carNum = @"";
    _imageFirst = @"";
    _imageSecond = @"";
    _imageThird = @"";
    _firstImg = nil;
    _secondImg = nil;
    _thirdImg = nil;
    [self creatUI];
}

- (void)creatUI
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"实名认证";
    self.view.backgroundColor = BacksColor;
    NSArray *titiAry = @[@"真实姓名",@"身份证号码"];
    NSArray *pladerAry = @[@"请输入真实姓名",@"请输入您的居民身份证号码"];
    for (int i = 0; i < titiAry.count; i ++)
    {
        UIView *backView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 10*displaywidth+i*55*displaywidth, SCREEN_WIDTH, 45*displaywidth)];
        backView1.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:backView1];
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(0, 5*displaywidth, 95*displaywidth, 35*displaywidth) Font:15.0 Text:titiAry[i] Color:BlaTitColor];
        nameLab.textAlignment = NSTextAlignmentRight;
        [backView1 addSubview:nameLab];
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(100*displaywidth, 12.5*displaywidth, 1, 20*displaywidth)];
        line1.backgroundColor = RGB(204, 204, 204);
        [backView1 addSubview:line1];
        UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(110*displaywidth, 2.5*displayheight, SCREEN_WIDTH-125*displaywidth, 40*displayheight) placeholder:pladerAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
        [textfield setValue:RGB(135, 135, 135) forKeyPath:@"_placeholderLabel.textColor"];
        textfield.delegate = self;
        textfield.tag = 10+i;
        textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
        textfield.textColor = RGB(48, 48, 48);
        textfield.textAlignment = NSTextAlignmentLeft;
        [backView1 addSubview:textfield];
    }
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 120*displaywidth, SCREEN_WIDTH, 140*displaywidth)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 100*displaywidth, 35*displaywidth) Font:15.0 Text:@"居民身份证照片" Color:BlaTitColor];
    [bottomView addSubview:titLab];
    NSArray *imgtitAry = @[@"身份证正面照",@"身份证背面照",@"手持身份证照"];
    CGFloat width = (SCREEN_WIDTH-60*displaywidth)/3;
    for (int i = 0; i < imgtitAry.count; i++)
    {
        UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth+(width+15*displaywidth)*i, 55*displaywidth, width, 70*displaywidth)];
        backV.backgroundColor = RGB(245, 245, 245);
        backV.layer.cornerRadius = 5;
        backV.layer.masksToBounds = YES;
        [bottomView addSubview:backV];
        UIImageView *imgV = [ZCControl createImageViewWithFrame:CGRectMake(width/2-15*displaywidth, 10*displaywidth, 30*displaywidth, 30*displaywidth) ImageName:@"my_icon07"];
        imgV.contentMode = UIViewContentModeScaleAspectFit;
        [backV addSubview:imgV];
        UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(0, 40*displaywidth, width, 30*displaywidth) Font:12.0 Text:imgtitAry[i] Color:RGB(32, 69, 139)];
        titlab.textAlignment = NSTextAlignmentCenter;
        [backV addSubview:titlab];
        UIImageView *cardImgview = [ZCControl createImageViewWithFrame:CGRectMake(0, 0, width, 70*displaywidth) ImageName:nil];
        cardImgview.backgroundColor = [UIColor clearColor];
        cardImgview.contentMode = UIViewContentModeScaleAspectFill;
        cardImgview.layer.cornerRadius = 5;
        cardImgview.layer.masksToBounds = YES;
        [backV addSubview:cardImgview];
        if (i == 0)
        {
            firstImgview = cardImgview;
        }
        else if (i == 1)
        {
            secondImgview = cardImgview;
        }
        else
        {
            thirdImgview = cardImgview;
        }
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, width, 70*displayheight) ImageName:nil Target:self Action:@selector(pushAction:) Title:nil Font:12.0];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 200+i;
        [cardImgview addSubview:btn];
    }
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"提交认证" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [self.view addSubview:soureBtn];
}

- (void)pushAction:(UIButton *)btn
{
    _phoneType = btn.tag-200;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    WEAKSELF;
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [weakSelf takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [weakSelf choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}


-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (_phoneType == 0)
    {
        _firstImg = image;
        firstImgview.image = image;
    }
    else if(_phoneType == 1)
    {
        _secondImg = image;
        secondImgview.image = image;
    }
    else
    {
        _thirdImg = image;
        thirdImgview.image = image;
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}


//提交认证
- (void)soureBtnAction
{
    [self.view endEditing:YES];
    if ([_name isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入真实姓名" addToView:self.view];
        return;
    }
    if ([_carNum isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入身份证号码" addToView:self.view];
        return;
    }
    if (_firstImg == nil)
    {
        [LTools showMBProgressWithText:@"请上传身份证正面照" addToView:self.view];
        return;
    }
    if (_secondImg == nil)
    {
        [LTools showMBProgressWithText:@"请上传身份证背面照" addToView:self.view];
        return;
    }
    if (_thirdImg == nil)
    {
        [LTools showMBProgressWithText:@"请上传手持身份证照" addToView:self.view];
        return;
    }
    WEAKSELF;
    NSArray *imgAry = @[_firstImg,_secondImg,_thirdImg];
    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];
    [HttpTool uploadImageWithPath:@"/file/upload" params:nil thumbName:@"file" ImageAry:imgAry success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         NSArray *imgArray = json[@"data"];
         if (imgArray.count < 3)
         {
             [LTools showMBProgressWithText:@"图片上传出现问题，请重新上传" addToView:weakSelf.view];
             return;
         }
         
         if ([json server_Getcodecheck])
         {
             NSDictionary *dic = @{@"realName":_name,
                                   @"idCard":_carNum,
                                   @"idCardFrontImg":imgArray[0],
                                   @"idCardReverseImg":imgArray[1],
                                   @"idCardImg":imgArray[2]};
             [self requestRealName:dic];
         }
         else
         {
             [LTools showMBProgressWithText:json[@"msg"] addToView:weakSelf.view];
         }
     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
     } progress:^(CGFloat progress) {
         
     }];
}

- (void)requestRealName:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_identity Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"提交成功" addToView:sharedDelegate.window];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 10)
    {
        _name = textField.text;
    }
    else if (textField.tag == 11)
    {
        _carNum = textField.text;
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
